package cn.flightcloud.auth.config.spring.security.service;

import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.util.Assert;

/**
 * 可缓存的UserDetailsService
 * 
 * @author chenjj
 *
 */
public class CachingUserDetailsService implements UserDetailsService {

	private UserCache userCache = new NullUserCache();
	private final UserDetailsService delegate;

	public CachingUserDetailsService(UserDetailsService delegate) {
		this.delegate = delegate;
	}

	public CachingUserDetailsService(UserDetailsService delegate, UserCache userCache) {
		this.delegate = delegate;
		this.userCache = userCache;
	}

	public UserCache getUserCache() {
		return userCache;
	}

	public void setUserCache(UserCache userCache) {
		this.userCache = userCache;
	}

	/**
	 * @see UserDetailsService
	 */
	@Override
	public UserDetails loadUserByUsername(String username) {
		// get userDetails from userCache
		UserDetails user = userCache.getUserFromCache(username);
		// if userCache not found
		if (user == null) {
			// invoke delete’s loadUserByUsername
			user = delegate.loadUserByUsername(username);
		}

		Assert.notNull(user, "UserDetailsService " + delegate + " returned null for username " + username + ". "
				+ "This is an interface contract violation");
		// put user into userCache
		userCache.putUserInCache(user);

		return user;
	}
}
